package com.yy.job.core.config.validator;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import com.google.common.collect.Lists;
import com.yy.job.common.enums.ErrorCodeEnum;
import com.yy.job.core.config.xml.JobXmlConfig;
import com.yy.job.core.config.xml.ModuleXmlConfig;
import com.yy.job.utils.DataValidator;
import com.yy.job.utils.exception.YYJobRuntimeException;

/**
 * 校验器
 * 
 * @author eleven.li
 *
 */
public class ModuleXmlConfigValidator {

	public static void validate(ModuleXmlConfig moduleXmlConfig) {
		if (moduleXmlConfig == null) {
			throw new YYJobRuntimeException(ErrorCodeEnum.CHECK_MODULE_ERROR, "no moduleJobConfig");
		}
		String moduleCode = moduleXmlConfig.getModuleCode();
		if (StringUtils.isBlank(moduleCode)) {
			throw new YYJobRuntimeException(ErrorCodeEnum.CHECK_MODULE_ERROR, "moduleCode is empty");
		}
		if (StringUtils.isBlank(moduleXmlConfig.getModuleName())) {
			throw new YYJobRuntimeException(ErrorCodeEnum.CHECK_MODULE_CONFIG, moduleCode, "moduleName is empty");
		}

		if (StringUtils.isNotBlank(moduleXmlConfig.getJobWorkerSize())
				&& !DataValidator.isPosInteger(moduleXmlConfig.getJobWorkerSize())) {
			throw new YYJobRuntimeException(ErrorCodeEnum.CHECK_MODULE_CONFIG, moduleCode,
					"jobWorkerSize is not positive integer");
		}
		if (CollectionUtils.isEmpty(moduleXmlConfig.getJobConfigs())) {
			throw new YYJobRuntimeException(ErrorCodeEnum.CHECK_MODULE_CONFIG, moduleCode, "no jobconfigs");
		}

		List<String> jobCodeList = Lists.newArrayList();
		for (JobXmlConfig jobConfig : moduleXmlConfig.getJobConfigs()) {
			// 校验jobConfig节点的配置
			JobXmlConfigValidator.validate(moduleCode, jobConfig);

			// 校验jobeCode是否重复
			String jobCode = jobConfig.getJobCode();
			if (jobCodeList.contains(jobCode)) {
				throw new YYJobRuntimeException(ErrorCodeEnum.CHECK_JOB_CONFIG, moduleCode, jobCode,
						"jobCode is duplicated");
			}
			jobCodeList.add(jobCode);
		}
	}

}
